<script lang="ts" setup>
import apply from '@/api/apply'
import { useApplyStore } from '@/store'

const { applyId } = storeToRefs(useApplyStore())
const visible = ref(false)
const innerValue = ref([])
const innerText = ref('')

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false
  },
  inputAlign: {
    type: String,
    default: 'left',
  },
})

const prov = defineModel('prov', { type: String })
const city = defineModel('city', { type: String })
const dist = defineModel('dist', { type: String })

function clickInput() {
  if (!props.disabled) {
    visible.value = true
  }
}

const initingText = '初始化中...'
const initing = ref(false)
const areaList = ref([])
const outputText = ref('')

// 加载中就显示加载文字
watch(() => initing.value, (value) => {
  if (value) {
    outputText.value = initingText
  } else {
    outputText.value = innerText.value
  }
})

async function initData() {
  initing.value = true
  const provNode = areaList.value.find(x => x.areaCode === prov.value)
  if (provNode) {
    const provText = provNode.areaAll
    const { data } = await apply.getAddressCascade(applyId.value, prov.value)
    if (data.status === 'success') {
      const cityNode = data.data.areaList.find(x => x.areaCode === city.value)
      const cityText = cityNode.areaAll
      const { data: req } = await apply.getAddressCascade(applyId.value, city.value)
      if (req.status === 'success') {
        const distNode = req.data.areaList.find(x => x.areaCode === dist.value)
        const distText = distNode.areaAll
        innerText.value = `${provText},${cityText},${distText}`
        initing.value = false
      }
      else {
        initing.value = false
      }
    }
    else {
      initing.value = false
    }
  } else {
    initing.value = false
    outputText.value = ''
  }
}

watch(() => prov.value, async () => {
  await initData()
})
watch(() => city.value, async () => {
  await initData()
})
watch(() => dist.value, async () => {
  await initData()
})

function pathChange(pathNodes: any) {
  if (pathNodes.length >= 3 && pathNodes[pathNodes.length - 1] !== null) {
    innerText.value = pathNodes.map(item => item.text).join(',')
    prov.value = pathNodes[0].value
    city.value = pathNodes[1].value
    dist.value = pathNodes[2].value
  }
}

async function lazyLoad(node: any, resolve: (children: any) => void) {
  const { data } = await apply.getAddressCascade(applyId.value, '')
  if (data.status === 'success') {
    // 把areaList存起来
    areaList.value = data.data.areaList
    // root表示第一层数据
    if (node.root) {
      if (prov.value !== '') {
        await initData()
      }
      resolve(data.data.areaList.map((item) => {
        return {
          value: item.areaCode,
          text: item.areaAll,
        }
      }))
    }
    else {
      const { value, level } = node
      const { data: req } = await apply.getAddressCascade(applyId.value, value)
      if (req.status === 'success') {
        resolve(req.data.areaList.map((item) => {
          return {
            value: item.areaCode,
            text: item.areaAll,
            leaf: level >= 3,
          }
        }))
      }
    }
  }
}
</script>

<template>
  <nut-input v-model="outputText" placeholder="请选择省市区" readonly :disabled="props.disabled" @click-input="clickInput"
    :input-align="props.inputAlign" placeholder-style="color:#ccc;" />
  <nut-cascader v-model:visible="visible" v-model="innerValue" title="省市区选择" lazy :lazy-load="lazyLoad"
    @path-change="pathChange" />
</template>
